package com.way.fileexplorer.activities;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.way.fileexplorer.R;
import com.way.fileexplorer.adapters.MultiSelectFileAdapter;
import com.way.fileexplorer.adapters.QuickScanCursorAdapter;
import com.way.fileexplorer.util.ActivityUtils;
import com.way.fileexplorer.util.FileType;
import com.way.fileexplorer.util.FileUtil;
import com.way.fileexplorer.util.IntentUtil;

public class MultiSelectActivity extends Activity implements OnClickListener,
		OnItemClickListener {
	private ListView mListView;
	private MultiSelectFileAdapter mAdapter;
	private QuickScanCursorAdapter mAdapterForOverView;
	private CheckBox mSelectAllFileCb;
	private ArrayList<File> mSelectedFiles = new ArrayList<File>();
	private TextView selectAllFileTx;
	public final static int MULTI_DELETE = 20;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.multi_select_activity);
		mListView = (ListView) findViewById(R.id.list);
		mSelectAllFileCb = (CheckBox) findViewById(R.id.select_all_cb);
		selectAllFileTx = (TextView) findViewById(R.id.selece_all_file);
		mSelectAllFileCb.setOnClickListener(this);
		if (getIntent().getStringExtra("path") != null) {
			String path = getIntent().getStringExtra("path");
			int top = getIntent().getIntExtra("position", 0);
			if (path != null) {
				File file = new File(path);
				mAdapter = MultiSelectFileAdapter
						.getMultiSelectFileAdapter(this);
				mAdapter.init(file);
				mListView.setAdapter(mAdapter);
				mListView.setSelection(top);
				mListView.setOnItemClickListener(this);
			}
		} else if (getIntent().hasExtra("fileType")) {
			int fileType = getIntent().getIntExtra("fileType", -1);
			int top = getIntent().getIntExtra("position", 0);
			switch (fileType) {
			case FileType.FILE_TYPE_IMAGE:
				mAdapterForOverView = new QuickScanCursorAdapter(this,
						QuickScanCursorAdapter.RESOURCE_IMAGE, top,
						mListView, true);
				break;
			case FileType.FILE_TYPE_AUDIO:
				mAdapterForOverView = new QuickScanCursorAdapter(this,
						QuickScanCursorAdapter.RESOURCE_AUDIO, top,
						mListView, true);
				break;
			case FileType.FILE_TYPE_VIDEO:
				mAdapterForOverView = new QuickScanCursorAdapter(this,
						QuickScanCursorAdapter.RESOURCE_VIDEO, top,
						mListView, true);
				break;
			case FileType.FILE_TYPE_DOC:
                mAdapterForOverView = new QuickScanCursorAdapter(this,
                        QuickScanCursorAdapter.RESOURCE_DOC, top,
                        mListView, true);
				break;
			case FileType.FILE_TYPE_PACKAGE:
                mAdapterForOverView = new QuickScanCursorAdapter(this,
                        QuickScanCursorAdapter.RESOURCE_APK, top,
                        mListView, true);
			}
			mListView.setAdapter(mAdapterForOverView);
			mListView.setOnItemClickListener(this);
			this.invalidateOptionsMenu();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if (mAdapter != null) {
			if (mAdapter.isChecked(position)) {
				if (mAdapter.isAllChecked()) {
					mSelectAllFileCb.setChecked(false);
					selectAllFileTx.setText(R.string.select_all);
				}
				mAdapter.setChecked(position, false);
				mSelectedFiles.remove(mAdapter.getItem(position));
			} else {
				mSelectedFiles.add((File) mAdapter.getItem(position));
				mAdapter.setChecked(position, true);
				if (mSelectedFiles.size() == mAdapter.getCount()) {
					mSelectAllFileCb.setChecked(true);
					selectAllFileTx.setText(R.string.unselect_all);
				}
			}
			this.invalidateOptionsMenu();
			mAdapter.notifyDataSetChanged();
		} else if (mAdapterForOverView != null) {
			if (mAdapterForOverView instanceof QuickScanCursorAdapter) {
				if (mAdapterForOverView.isChecked(position)) {
					if (mAdapterForOverView.isAllChecked()) {
						mSelectAllFileCb.setChecked(false);
						selectAllFileTx.setText(R.string.select_all);
					}
					mAdapterForOverView.setChecked(position, false);
					mSelectedFiles.remove(mAdapterForOverView.getFile(position));
				} else {
					mSelectedFiles.add(mAdapterForOverView.getFile(position));
					mAdapterForOverView.setChecked(position, true);
					if (mSelectedFiles.size() == mAdapterForOverView.getCount()) {
						mSelectAllFileCb.setChecked(true);
						selectAllFileTx.setText(R.string.unselect_all);
					}
				}
				mAdapterForOverView.notifyDataSetChanged();
			}
			this.invalidateOptionsMenu();
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == mSelectAllFileCb) {
			if (mAdapter != null) {
				if (mAdapter.isAllChecked() == true) {
					selectAllFileTx.setText(R.string.select_all);
					mSelectedFiles.clear();
					mAdapter.checkAll(false);
				} else {
					selectAllFileTx.setText(R.string.unselect_all);
					mSelectedFiles.clear();
					for (int i = 0; i < mAdapter.getCount(); i++) {
						mSelectedFiles.add((File) mAdapter.getItem(i));
					}
					mAdapter.checkAll(true);
				}
				mAdapter.notifyDataSetChanged();
			} else if (mAdapterForOverView != null) {
				if (mAdapterForOverView instanceof QuickScanCursorAdapter) {
					if (mAdapterForOverView.isAllChecked() == true) {
						selectAllFileTx.setText(R.string.select_all);
						mSelectedFiles.clear();
						mAdapterForOverView.checkAll(false);
					} else {
						selectAllFileTx.setText(R.string.unselect_all);
						mSelectedFiles.clear();
						for (int i = 0; i < mAdapterForOverView.getCount(); i++) {
							mSelectedFiles.add((File) mAdapterForOverView.getFile(i));
						}
						mAdapterForOverView.checkAll(true);
					}
					mAdapterForOverView.notifyDataSetChanged();
				} 
			}
			invalidateOptionsMenu();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.multi_select_menu, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (menu != null) {
			MenuItem multiSelectItem = menu.findItem(R.id.menu_delete);
			MenuItem copySelectItem = menu.findItem(R.id.menu_copy);
			MenuItem cutSelectItem = menu.findItem(R.id.menu_cut);
			MenuItem installSelectItem = menu.findItem(R.id.menu_install);
			MenuItem shareSelectItem = menu.findItem(R.id.menu_share);
			if(getIntent().getIntExtra("fileType", -1) != FileType.FILE_TYPE_PACKAGE){
			    if(installSelectItem != null){
			        installSelectItem.setVisible(false);
			    }
			}
			if(mAdapterForOverView == null){
			    if(shareSelectItem != null){
				shareSelectItem.setVisible(false);
			    }
			}
			if (mSelectedFiles != null && !mSelectedFiles.isEmpty()) {
				if (multiSelectItem != null) {
					multiSelectItem.setEnabled(true);
				}
				if (copySelectItem != null) {
					copySelectItem.setEnabled(true);
				}
				if (cutSelectItem != null) {
					cutSelectItem.setEnabled(true);
				}
				if(shareSelectItem != null && shareSelectItem.isVisible()){
				    shareSelectItem.setEnabled(true);
				}
				if(installSelectItem != null && installSelectItem.isVisible()){
					installSelectItem.setEnabled(true);
				}
			} else {
				if (multiSelectItem != null) {
					multiSelectItem.setEnabled(false);
				}
				if (copySelectItem != null) {
					copySelectItem.setEnabled(false);
				}
				if (cutSelectItem != null) {
					cutSelectItem.setEnabled(false);
				}
				if(installSelectItem != null){
					if(installSelectItem.isVisible()){
	                    			installSelectItem.setEnabled(false);
	                		}
				}
				if(shareSelectItem != null){
					if(shareSelectItem.isVisible()){
	                    			shareSelectItem.setEnabled(false);
	                		}
				}
			}
		}
		return super.onPrepareOptionsMenu(menu);
	}

	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			MultiSelectActivity.this.finish();
			ActivityUtils.startPasteMode(which);
		}
	};

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_delete: {
		    new AlertDialog.Builder(this)
            .setTitle(R.string.operate_delete)
            .setMessage(R.string.confirm_delete)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialog, int which) {
//                     TODO Auto-generated method stub
                    Intent intent = new Intent();
                    intent.putExtra("selectedFiles", mSelectedFiles);
                    intent.putExtra("operation", R.id.menu_delete);
                    setResult(RESULT_OK, intent);
                    finish();
                }
                
            })
            .setNegativeButton(android.R.string.cancel, null)
            .show();
			return true;
		}
		case R.id.menu_copy: {
			FileUtil.copy(this, mSelectedFiles, false);
			Intent intent = new Intent();
            intent.putExtra("selectedFiles", mSelectedFiles);
            intent.putExtra("operation", R.id.menu_copy);
            setResult(RESULT_OK, intent);
            finish();
			return true;
		}
		case R.id.menu_cut: {
			FileUtil.copy(this, mSelectedFiles, true);
			Intent intent = new Intent();
            intent.putExtra("selectedFiles", mSelectedFiles);
            intent.putExtra("operation", R.id.menu_copy);
            setResult(RESULT_OK, intent);
            finish();
			return true;
		}
		
		case R.id.menu_install:{
			if(mAdapterForOverView != null && mSelectedFiles != null && !mSelectedFiles.isEmpty()){
                for(File file: mSelectedFiles){
                    Intent intent = IntentUtil.getIntentByFileType(MultiSelectActivity.this, FileType.FILE_TYPE_PACKAGE, file);
                    if(intent != null) {
                        startActivity(intent);
                    } else {
                        Toast.makeText(MultiSelectActivity.this, R.string.msg_invalid_intent, Toast.LENGTH_SHORT).show();
                    }
                }
                finish();
            }
			
			return true;
		}
		case R.id.menu_share:{
            Intent intent=new Intent(Intent.ACTION_SEND_MULTIPLE);
            String type = FileType.getFileType(this).getTypeByFile(mSelectedFiles.get(0));
            ArrayList<Uri> sharedUris = new ArrayList<Uri>();
            for(File file:mSelectedFiles){
                Uri uri = Uri.parse("file://" + file.getPath());
                sharedUris.add(uri);
            }
            intent.setType(type);
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, sharedUris);
            startActivity(Intent.createChooser(intent, this.getResources().getString(R.string.operate_share)));
            finish();
            return true;
		}
		default:
		    return false;
		}
		//return super.onOptionsItemSelected(item);
	}
}
